package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUserRealname;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class)//RuntimeException.class
//    @Transactional
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1 参数检查
        if (dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "实名认证id不存在");
        }
        //2.查询当前认证用户是否存在APP端有当前用户
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId, dto.getId())
                .eq(ApUserRealname::getStatus, 1)//审核未通过的用户
        );
        if (apUserRealname == null) {
//            log.error("待审核 实名认证信息不存在 userRealnameId:{}",dto.getId());
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {//如果并不等于1 说明不是待审核状态
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "实名认证信息不是待审核状态");
        }
        //1.2根据ap_user_realname中关联的userId查询ap_user
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息所关联的app账户不存在");

        }
        //2.修改ap_user_realname表status状态 9
        apUserRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);//修改实名认证状态

        //3如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //3.1 开通自媒体账户信息
            WmUser wmUser = createWmUser(apUser);

            //3.2创建作者信息
            createAuthor(apUser,wmUser);
        }


        return ResponseResult.okResult();

    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        //1.查询作者信息是否已经存在
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if(result.getCode().intValue()!=0){//说明远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }

        ApAuthor apAuthor = result.getData();
        if(apAuthor!=null){
            //2.如果已经创建 抛异常数据存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //2.如果不存在  就创建作者信息
        apAuthor=new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);//平台自媒体人
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());

        ResponseResult responseResult = articleFeign.save(apAuthor);
        if(responseResult.getCode().intValue() !=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,responseResult.getErrorMessage());
        }


    }


    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        //1.根据用户名 查询 wmUser是否已经创建（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if(result.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if(wmUser!=null){
            //2.如果已经创建 抛异常数据存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //3.创建wmUser信息 保存
        wmUser=new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId());//关联的app账户id
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> responseResult = wemediaFeign.save(wmUser);
        if(responseResult.getCode().intValue()!=0){//说明远程调用失败
            CustException.cust(
                    AppHttpCodeEnum.REMOTE_SERVER_ERROR,responseResult.getErrorMessage()
            );

        }
        return responseResult.getData();//返回保存成功的自媒体账户信息
    }

    /**
     * 查询列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> resultPage = page(page, lambdaQueryWrapper);
        // 3 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                resultPage.getTotal(), resultPage.getRecords());
    }
}